<template>
  <view 
    class="drag-home-button"
    :style="buttonStyle"
    @touchstart="onTouchStart"
    @touchmove="onTouchMove"
    @touchend="onTouchEnd"
    @click="onClick"
  >
    <uni-icons type="home" size="30" color="#ffffff" />
  </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { ref, reactive, computed, onMounted } from 'vue';

// 按钮状态
const isDragging = ref(false);
const startX = ref(0);
const startY = ref(0);
const offsetX = ref(0);
const offsetY = ref(0);
const windowSize = reactive({
  width: 0,
  height: 0
});
const buttonSize = 100; // 按钮大小（rpx）

// 计算按钮样式
const buttonStyle = computed(() => {
  return {
    top: `${offsetY.value}px`,
    left: `${offsetX.value}px`
  };
});

// 初始化窗口大小
onLoad(() => {
  const { windowWidth, windowHeight } = uni.getSystemInfoSync();
  windowSize.width = windowWidth;
  windowSize.height = windowHeight;
  // 默认位置：右下角
  offsetX.value = windowWidth - 70;
  offsetY.value = windowHeight - buttonSize; 
  
});

// 触摸开始
const onTouchStart = (e: TouchEvent) => {
  isDragging.value = true;
  const touch = e.touches[0];
  startX.value = touch.clientX - offsetX.value;
  startY.value = touch.clientY - offsetY.value;
};

// 触摸移动
const onTouchMove = (e: TouchEvent) => {
  if (!isDragging.value) return;
  
  const touch = e.touches[0];
  let newX = touch.clientX - startX.value;
  let newY = touch.clientY - startY.value;
  
  // 限制在屏幕范围内
  newX = Math.max(0, Math.min(newX, windowSize.width - buttonSize/2));
  newY = Math.max(0, Math.min(newY, windowSize.height - buttonSize/2));
  
  offsetX.value = newX;
  offsetY.value = newY;
};

// 触摸结束
const onTouchEnd = () => {
  isDragging.value = false;
};

// 点击事件 - 返回首页
const onClick = () => {
  // 防止拖拽时误触
  if (isDragging.value) return;
  
  uni.switchTab({
    url: '/pages/user/index'
  });
};
</script>

<style scoped lang="scss">
.drag-home-button {
  position: fixed;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #007AFF 0%, #0056D6 100%);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 122, 255, 0.4);
  z-index: 9999;
  cursor: move;
  transition: transform 0.1s ease-out;
  touch-action: none; // 防止触摸时页面滚动
  
  // 添加点击反馈
  &:active {
    transform: scale(0.95);
  }
}
</style>